package com.zxmc.server.service.impl;

import com.alibaba.fastjson2.JSON;
import com.zxmc.common.context.BaseContext;
import com.zxmc.pojo.dto.NovelQueryDto;
import com.zxmc.pojo.entity.*;
import com.zxmc.server.mapper.AuthorMapper;
import com.zxmc.server.mapper.BookShelfMapper;
import com.zxmc.server.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
public class BookShelfServiceImpl implements BookShelfService {

    @Autowired
    private BookShelfMapper bookShelfMapper;
    @Autowired
    private ReadingHistoryService readingHistoryService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private NovelService novelService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public List<BookShelf> list(Integer id) {
        Integer userId = BaseContext.getCurrentId();
        return bookShelfMapper.list(userId,id);
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"novelCache"},key = "#novelId",beforeInvocation = true)
    @Override
    public void insert(Integer novelId) {
        Object object=redisTemplate.opsForValue().get("novelHistory:"+BaseContext.getCurrentId()+":"+novelId);
        ReadingHistory list = JSON.to(ReadingHistory.class, object);
        BookShelf bookShelf = BookShelf.builder().userId(BaseContext.getCurrentId()).novelId(novelId).build();

        Novel novel = novelService.list(NovelQueryDto.builder().id(novelId).build()).get(0);
        bookShelf.setTitle(novel.getTitle());
        bookShelf.setAuthor(novel.getAuthor());
        bookShelf.setTotal(novel.getTotal());
        bookShelf.setCover(novel.getCover());
        bookShelf.setAddedTime(LocalDateTime.now());

        bookShelf.setChapterTotal(chapterService.getTotal(novelId));
        Chapter chapter = null;
        if(list!=null){
            bookShelf.setLastReadTime(list.getLastReadTime());
            bookShelf.setLastReadTitle(list.getLastReadTitle());
            bookShelf.setLastRead(list.getLastRead());

            chapter= chapterService.listOnly(novelId, list.getLastRead());

        }else {
            chapter= chapterService.listOnly(novelId, 1);
        }
        bookShelf.setLastReadContent(chapter.getContent().substring(0,100)+"...");
        bookShelfMapper.insert(bookShelf);
//        Random random = new Random();
//        // 生成一个 50 到 149 之间的随机整数
//        int randomInt = random.nextInt(5)+5;
        novel.setCollectNum(novel.getCollectNum()+1);
        novelService.update(novel);
    }

    @Caching(
            evict = {
                    @CacheEvict(value = "novelCache", key = "#novelId"),
                    @CacheEvict(value = "novelPageCache", allEntries = true),
            }
    )
    @Override
    public void delete(Integer novelId) {
        Novel novel = novelService.list(NovelQueryDto.builder().id(novelId).build()).get(0);
        BookShelf bookShelf = BookShelf.builder().userId(BaseContext.getCurrentId()).novelId(novelId).build();
        bookShelfMapper.delete(bookShelf);
        if(novel.getCollectNum()>0)
            novel.setCollectNum(novel.getCollectNum()-1);
        novelService.update(novel);
    }


    @Override
    public void update(ReadingHistory list) {
        BookShelf bookShelf=new BookShelf();
        bookShelf.setLastReadTime(list.getLastReadTime());
        bookShelf.setLastReadTitle(list.getLastReadTitle());
        bookShelf.setLastRead(list.getLastRead());

        Chapter chapter = chapterService.listOnly(list.getNovelId(), list.getLastRead());
        bookShelf.setLastReadContent(chapter.getContent().substring(0,100)+"...");
        bookShelf.setUserId(BaseContext.getCurrentId());
        bookShelf.setNovelId(list.getNovelId());
        bookShelfMapper.update(bookShelf);
    }

//    @CacheEvict(value = {"novelCache", "novelPageCache"},allEntries = true)
    @Override
    public void deleteByUser(User user) {
        BookShelf bookShelf = BookShelf.builder().userId(user.getId()).build();
        bookShelfMapper.delete(bookShelf);
    }

    @Override
    public void deleteAll(Integer novelId) {
        Novel novel = novelService.listById(novelId);
        BookShelf bookShelf = BookShelf.builder().novelId(novelId).build();
        bookShelfMapper.delete(bookShelf);
        if(novel.getCollectNum()>0)
            novel.setCollectNum(novel.getCollectNum()-1);
        novelService.update(novel);
    }
}
